package com.orange.off.cloud.cloudoff.fragments;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.orange.off.cloud.cloudoff.R;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 个人中心------关于我们
 *
 * @author qs
 */
public class PersonalAboutUsFragment extends Fragment {

    @Bind(R.id.imageView1)
    ImageView imageView1;
    @Bind(R.id.version_number)
    TextView versionNumber;
    @Bind(R.id.update_relative)
    RelativeLayout updateRelative;
    @Bind(R.id.rt_aboutusBack)
    RelativeLayout rtAboutusBack;
    private ProgressDialog progressDialog;
    File sdcardTempFile;
    /**
     * 可取消的任务
     */
    //private Callback.Cancelable cancelable;

    /**
     * 进度条对话框
     */
    private ProgressDialog progress;

    public static PersonalAboutUsFragment newInstance() {
        PersonalAboutUsFragment fragment = new PersonalAboutUsFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.myaboutusfragment, container, false);
        ButterKnife.bind(this, view);
        initProgressDialog();
        return view;
    }


    private void initViews() {
       /* sdcardTempFile = new File(MyApplication.FILE_PATH + File.separator + "orange.apk");
        try {
            versionNumber.setText(getVersionName());
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

   /* void IsUpdate() {
        RequestParams params = new RequestParams(Ip.update);
        params.addBodyParameter("a", "apk_get");
        params.addBodyParameter("type", MyApplication.VERSION);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgressDialog();
                final JSONObject jsonObject = JSON.parseObject(result);
                int status = jsonObject.getInteger("status");//1：有新版本需要更新   2：没有最新版本
                Log.d("debug", result);

                if (1 == status) {
                    Log.d("debug", "status--->" + status);
                    //1.实例化Builder对象：
                    AlertDialog.Builder builder = new AlertDialog.Builder(AboutUsActivity.this);
                    builder.setTitle("金橙提示");
                    builder.setMessage("有新版本，是否更新");
                    builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Update(jsonObject.getString("url"));
                        }
                    });
                    builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();//展示对话框
                } else {
                    ToastUtils.show(getApplicationContext(), "已经是最新版本");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                hideProgressDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                hideProgressDialog();
            }

            @Override
            public void onFinished() {
                hideProgressDialog();
            }
        });
    }*/


    /*void Update(String url) {
        RequestParams params = new RequestParams(url);
        params.setAutoResume(true);//设置是否在下载是自动断点续传
        params.setAutoRename(false);//设置是否根据头信息自动命名文件
        params.setSaveFilePath(sdcardTempFile.getPath());
        params.setExecutor(new PriorityExecutor(2, true));//自定义线程池,有效的值范围[1, 3], 设置为3时, 可能阻塞图片加载.
        params.setCancelFast(true);//是否可以被立即停止.
        cancelable = x.http().post(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File result) {
                //apk下载完成后，调用系统的安装方法
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    String cmd = "chmod 777 " + sdcardTempFile.getPath();
                    try {
                        Runtime.getRuntime().exec(cmd);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(android.content.Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(sdcardTempFile), "application/vnd.android.package-archive");
                startActivity(intent);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                progress.dismiss();
            }

            //网络请求之前回调
            @Override
            public void onWaiting() {
            }

            //网络请求开始的时候回调
            @Override
            public void onStarted() {
                progress.show();
            }

            //下载的时候不断回调的方法
            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                if (isDownloading) {
                    progress.setProgress((int) (current * 100 / total));
                }
            }
        });
    }

    @OnClick({R.id.tvBtnBack_wanchengqianyue, R.id.update_relative})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvBtnBack_wanchengqianyue:
                finish();
                break;
            case R.id.update_relative:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    MPermissionUtils.requestPermissionsResult(this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE}
                            , new MPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {
                                    showProgressDialog();
                                    IsUpdate();
                                }

                                @Override
                                public void onPermissionDenied() {
                                    MPermissionUtils.showTipsDialog(AboutUsActivity.this);
                                }
                            });
                } else {
                    showProgressDialog();
                    IsUpdate();
                }


                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }*/

    /*初始化对话框*/
    private void initProgressDialog() {
        //创建进度条对话框
        progress = new ProgressDialog(getActivity());
        //设置标题
        progress.setTitle("下载文件");
        //设置信息
        progress.setMessage("玩命下载中...");
        progress.setIndeterminate(false);
        progress.setCancelable(false);
        progress.setCanceledOnTouchOutside(false);
        //设置显示的格式
        progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //设置按钮
        progress.setButton(ProgressDialog.BUTTON_NEGATIVE, "暂停", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //点击取消正在下载的操作
                //cancelable.cancel();
            }
        });
    }

   /* public String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = getApplication().getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getApplication().getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }*/

    /**
     * 显示保存进度框
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("请求中……");
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    private void hideProgressDialog() {
        if (progressDialog != null) {
            progressDialog.hide();
        }
    }

    private void dismissProgressDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        dismissProgressDialog();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.rt_aboutusBack)
    public void onClick() {
        getActivity().finish();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            getActivity().finish();
            return true;
        }
        return false;
    }
}
